<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/9/30
 * Time: 11:38
 */
namespace app\api\service;

use app\api\model\ThirdApp;
use app\lib\exception\TokenException;


class AppToken extends Token
{
    /**
     * 获取第三方的token
     * @param $ac
     * @param $sc
     * @return mixed
     * @throws TokenException
     */
    public function getToken($ac,$sc){
        $app = ThirdApp::check($ac);
        if ($app->app_secret != md5($sc) || empty($app)){
            throw new TokenException([
                'code'=>201,
                'msg'=>'账号或密码错误',
                'error_code'=>10004
            ]);
        }else{
            //判断账号是否异常
            if (time()> $app->end_time){
                throw new TokenException([
                    'code'=>201,
                    'msg'=>'账号已过期',
                    'error_code'=>10006
                ]);
            }
            if ($app->status == 0){
                throw new TokenException([
                    'code'=>201,
                    'msg'=>'账号状态异常',
                    'error_code'=>10007
                ]);
            }
            $scope = $app->scope;
            $uid = $app->id;
            $values=[
              'scope'=>  $scope,
                'uid'=>  $uid
            ];
            $token = $this->saveToCache($values);
            return $token;
        }
    }

    /**
     * 根据ID获取token
     * @param $ac
     * @return string
     * @throws TokenException
     */
    public function getTokenById($ac){
       $app =  ThirdApp::check($ac);
        if (empty($app)) {
            throw new TokenException([
                'code' => 201,
                'msg' => '账号或密码错误',
                'error_code' => 10004
            ]);
        }
            $scope = $app->scope;
        $uid = $app->id;
        $values=[
            'scope'=>  $scope,
            'uid'=>  $uid
        ];
        $token = $this->saveToCache($values);
        return $token;
    }


    /**
     * 存储缓存，并返回token
     * @param $values
     * @return string
     * @throws TokenException
     */
    private function saveToCache($values){
        $token = self::generateToken();
        $expire_in = config('setting.token_expire_in');
        $result = cache($token,json_encode($values),$expire_in);
        if (!$result){
            throw new TokenException([
                'msg'=>'服务器缓存异常',
                'err_code'=>'10005'
            ]);
        }
        return $token;
    }
}